import { useAsync } from "./use-async";
import { Project } from "screens/project-list/list";
import { useCallback, useEffect } from "react";
import { clearObject } from "./index";
import { useHttp } from "./http";

export const useProject = (param?: Partial<Project>) => {
  const client = useHttp();

  const { run, ...result } = useAsync<Project[]>();

  const fetchProjects = useCallback(() => {
    return client("projects", { data: clearObject(param || {}) });
  }, [client, param]);

  useEffect(() => {
    run(fetchProjects(), {
      retry: fetchProjects
    });
  }, [param, run, fetchProjects]);
  return result;
};

export const useEditProject = () => {
  const { run, ...asyncResult } = useAsync();
  const client = useHttp();
  const mutate = (params: Partial<Project>) => {
    return run(client(`projects/${params.id}`, {
      data: params,
      method: "PATCH"
    }));
  };
  return {
    mutate,
    ...asyncResult
  };
};

export const useAddProject = () => {
  const { run, ...asyncResult } = useAsync();
  const client = useHttp();
  const mutate = (params: Partial<Project>) => {
    run(client(`projects/${params.id}`, {
      data: params,
      method: "POST"
    }));
  };
  return {
    mutate,
    ...asyncResult
  };
};
